package com.xzq.socket.test.day01.nio;

import lombok.Data;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/19 9:02
 * @Version 1.0.0
 **/
@Data
public class ChannelHandler {
    private SocketChannel socketChannel;
    private Charset charset;
    public ChannelHandler(SocketChannel socketChannel,Charset charset) {
        this.socketChannel = socketChannel;
        this.charset = charset;
    }

    public void writeAndFlush(Object msg) {
        try {
            byte[] bytes = msg.toString().getBytes(charset);
            ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
            buffer.put(bytes);
            buffer.flip();
            socketChannel.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
